﻿using System.Runtime.InteropServices;
using System.Text;

namespace Rail.Commons.SerializeHelper
{
    public class IniHelper
    {
        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="section">节点名称[如[TypeName]]</param>
        /// <param name="key">键</param>
        /// <param name="val">值</param>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        public static extern bool WritePrivateProfileString(string section, string key, string val, string filepath);

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">节点名称</param>
        /// <param name="key">键</param>
        /// <param name="def">值</param>
        /// <param name="retval">stringbulider对象</param>
        /// <param name="size">字节大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        public static extern bool GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
        
        public static string DefaultInit
        {
            get
            {
                return Commons.Paths.ApplicationConfigDir + "\\default.ini";
            }
        }
        public static string GetVal(string section,string key)
        {
            StringBuilder sb = new StringBuilder();
            GetPrivateProfileString(section,key,string.Empty,sb,1024, DefaultInit);
            return sb.ToString();
        }
        public static void SetVal(string section,string key,string val)
        {
            WritePrivateProfileString(section, key, val, DefaultInit);
        }
    }
}